package com.zr.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.zr.constant.MessageConstant;
import com.zr.constant.RedisMessageConstant;
import com.zr.entity.Result;
import com.zr.pojo.Member;
import com.zr.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @auther zhaorui
 * @date 2019-12-01 - 20:01
 */
@RestController
@RequestMapping("/login")
public class LoginController {


    @Reference
    private MemberService memberService;
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/check")
    public Result check(@RequestBody Map map, HttpServletResponse response){
        //获取手机号
        String telephone = (String) map.get("telephone");
        //从Redis中获取数据
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //从map中获取用户输入的验证码
        String validateCode = (String) map.get("validateCode");

        // 将两个验证码进行比较
        if (codeInRedis == null || !codeInRedis.equals(validateCode)  ){
            //不同或者验证码为空
            return Result.error(MessageConstant.VALIDATECODE_ERROR);
        }

        //如果相同  需要判断会员表中是否有该用户   如果不是会员自动注册
        Member member = memberService.findMemberByTelephone(telephone);
        //如果为空 自动注册
        if (member == null){
            member.setRegTime(new Date());
            member.setPhoneNumber(telephone);

            memberService.add(member);
        }
        //登录之后 将用户的手机号存入cookie中
        Cookie cookie = new Cookie("login_member_telephone", telephone);
        cookie.setMaxAge(60*60*24*30);//30天有效
        cookie.setPath("/");
        response.addCookie(cookie);
        //将会员信息保存到Redis中  替代session
        //member对象不能直接添加到Redis中 先转成json
        String json = JSON.toJSON(member).toString();
        jedisPool.getResource().setex(telephone,300,json);
        return Result.ok(MessageConstant.LOGIN_SUCCESS);
    }
}
